import { Module, Global } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { RedisService } from './redis.service';
import { createClient } from 'redis';

@Global()
@Module({
  imports: [ConfigModule],
  providers: [
    {
      provide: 'REDIS_CLIENT',
      useFactory: async (configService: ConfigService) => {
        const redisConfig = configService.get('redis');
        const client = createClient({
          socket: {
            host: redisConfig.host,
            port: redisConfig.port,
            connectTimeout: redisConfig.connectTimeout,
            keepAlive: redisConfig.keepAlive,
            family: redisConfig.family,
          },
          commandsQueueMaxLength: 1000,
          password: redisConfig.password,
          database: redisConfig.db,
        });

        client.on('error', err => {
          console.error('Redis Client Error:', err);
        });

        client.on('connect', () => {
          console.log('✅ Redis连接成功');
        });

        client.on('disconnect', () => {
          console.log('❌ Redis连接断开');
        });

        await client.connect();
        return client;
      },
      inject: [ConfigService],
    },
    RedisService,
  ],
  exports: ['REDIS_CLIENT', RedisService],
})
export class RedisModule {}
